# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: loginViews.py
# @time: 2025/2/19 19:57
import re

from http.client import responses

import pymysql
from django.contrib.auth import authenticate, login
from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View


class loginView(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        remember=request.POST.get('remember')
        if not all([mobile,password]):
            return HttpResponseBadRequest('请输入完整的注册信息')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('请输入正确的手机号码')
        if not re.match(r'^[0-9A-Za-z]{6,20}$', password):
            return HttpResponseBadRequest('请输入6-20位的密码')

        user = authenticate(mobile=mobile, password=password)


        if user is None :
            return HttpResponseBadRequest('用户名或密码错误')
        login(request,user)
        responses=redirect(reverse('index'))
        if remember !=  "no":
            #不要求记录登录状态
            request.session.set_expiry(0)
            responses.set_cookie('is_login','true')
            responses.set_cookie('username',user.username,max_age=600*60*24*3)
        else:
            # 记录登录状态
            # 设置会话的过期时间为None，这意味着会话将在浏览器关闭时过期
            request.session.set_expiry(None)
            responses.set_cookie('is_login','true')
            responses.set_cookie('username',user.username,max_age=600*60*24*3)
        return responses

